<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        *{
            padding:0;
            margin:0;
        }
        html,body,.box{
            width: 100%;
            height:100%;
            overflow: hidden;
        }
        .box{
            position: relative;
        }

        .shadow{
            width:100px;
            height: 100px;
            background: orange;
            /* border-radius: 50%; */
            position: absolute;
            top:50px;
            left:50px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="shadow"></div>
    <!-- <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div> -->
    </div>


    <script>
        // 元素拖拽
        // 1. 先按下
        // 2. 鼠标滑动  改变对应的位置  left top
        // 3. 鼠标离开   松开  不再移动

        var shadow = document.getElementsByClassName('shadow')[0];
        var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
        var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        var maxLeft = clientWidth - shadow.clientWidth;    // 可以拖拽的 宽度
        var maxTop = clientHeight - shadow.clientHeight;  // 可以拖拽的 高度 



        shadow.onmousedown = function(e){
            var e = e  || window.event;

            var posX =  e.clientX;
            var posY = e.clientY;
            var offsetX = shadow.offsetLeft;
            var offsetY = shadow.offsetTop;
            
            var x = posX - offsetX;
            var y = posY - offsetY;

            // bug 
            document.onmousemove = function(e){
                var e = e  || window.event;
                

                var left = e.clientX - x;
                var top = e.clientY - y;
                console.log(left,top);

                if(left<0) left = 0;
                if(left>maxLeft) left = maxLeft;
                if(top<0) top = 0;
                if(top>maxTop) top = maxTop;
                

                shadow.style.left = left + "px"
                shadow.style.top = top  + 'px'
            }

            document.onmouseup = function(){
                document.onmousemove = null;
                document.onmouseup  = null;
            }
        }






    </script>
</body>
</html>